import { createRouter, createWebHashHistory } from 'vue-router'

const routes = [{
    path: '/',
    name: 'Home',
    component: () => import( /* webpackChunkName: "home" */ '@/views/home/Home'), // 动态路由、异步路由、路由懒加载
}, {
    path: '/login',
    name: 'Login',
    component: () => import( /* webpackChunkName: "login" */ '@/views/login/Login'),
    beforeEnter(to, from, next) { // 局部路由守卫
        const { isLogin } = localStorage;
        isLogin ? next({ name: 'Home' }) : next(); // 已登录直接进入主页
    }
}, {
    path: '/register',
    name: 'Register',
    component: () => import( /* webpackChunkName: "register" */ '@/views/register/Register'),
    beforeEnter(to, from, next) { // 局部路由守卫
        const { isLogin } = localStorage;
        isLogin ? next({ name: 'Home' }) : next(); // 已登录直接进入主页
    }
}, {
    path: '/shop/:id',
    name: 'Shop',
    component: () => import( /* webpackChunkName: "shop" */ '../views/shop/Shop')
}]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
    const { isLogin } = localStorage;
    if (isLogin || to.name == "Login" || to.name == "Register") { // 已经登录、登录页、注册页 => next()
        next();
    } else {
        next({ name: 'Login' })
    }
})

export default router